import { App } from 'vue';
import config from './axiosConfig';

export interface HttpConfig extends AnyObject {
  url: string,
  method?: string
}

export interface HttpFile {
  [key: string]: HttpConfig
}

export function useHttp() {
  const http: AnyObject = {};
  const lib = import.meta.globEager('./httplib/*.ts');

  for (const path in lib) {
    const file: HttpFile = lib[path].default;
    const name = path.split('/').slice(-1)[0].replace('.ts', '');

    for (const i in file) {
      if (!http[name]) http[name] = {};

      const { url, method } = file[i];

      http[name][i] = async (data: AnyObject, params: AnyObject, opt: AnyObject) => {
        return await config[method || 'get'](
          url, data, params, opt
        );
      };
    }

    return http;
  }
}

function install(app: App) {
  app.config.globalProperties.$api = useHttp();
}

export default {
  install
};
